from info import db, constants
from info.commons import user_login_data
from info.models import News, Category, User
from info.modules import news
from info.modules.profile import profile_blue
from flask import render_template, g, redirect, request, jsonify, current_app, session

# 功能描述：用户基本信息展示
from info.utils.image_storage import image_storage
from info.utils.response_code import RET

# 功能描述：获取我的关注
@profile_blue.route('/user_follow')
@user_login_data
def user_follow():
    # 获取参数
    page = request.args.get("p","1")
    # 校验参数，参数转换
    try:
        page = int(page)
    except Exception as e:
        page = 1
    # 分页查询用户的关注者
    try:
        paginate = g.user.followed.paginate(page,2,False)
    except Exception as e:
        return jsonify(errno=RET.DBERR,errmsg="分页失败")
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items
    # 携带数据渲染页面
    user_list = []
    for item in items:
        user_list.append(item.to_dict)
    data = {
        "total_page":totalPage,
        "current_page":currentPage,
        "user_list":user_list
    }

    return render_template("news/user_follow.html",data=data)



# 功能描述：作者新闻列表获取
@profile_blue.route('/other_news_list')
def other_news_list():
    # 获取参数
    page = request.args.get('p',"1")
    author_id = request.args.get("user_id")

    # 校验参数，为空校验
    if not author_id:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    try:
        page = int(page)
    except Exception as e:
        page = 1
    # 根据作者编号，取出作者对象，判断是否存在
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取作者对象失败")
    if not author:
        return jsonify(errno=RET.NODATA,errmsg="作者对象不存在")

    # 分页查询作者新闻列表
    try:
        # paginate= News.query.filter(News.user_id == author.id).order_by(News.create_time.desc()).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        paginate = author.news_list.order_by(News.create_time.desc()).paginate(page,2,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")
    # 获取分页对象属性，总页数，当前页，当前页对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items
    # 对象列表转字典列表
    news_list = []
    for item in items:
        news_list.append(item.to_dict())
    # 携带数据，返回响应
    data = {
        "totalPage":totalPage,
        "currentPage":currentPage,
        "news_list":news_list
    }
    return jsonify(errno=RET.OK,errmsg="获取成功",data=data)


# 功能描述：获取作者详情
@profile_blue.route('/other')
@user_login_data
def other():
    # 获取参数
    author_id = request.args.get("id")
    # 校验参数，为空校验
    if not author_id:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    # 根据编号取出作者对象
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取作者失败")
    # 判断作者对象是否存在
    if not author:return jsonify(errno=RET.NODATA,errmsg="作者不存在")

    # 判断该用户是否关注过该新闻的作者
    is_followed = False
    if g.user:
        if g.user in author.followers:
            is_followed = True

    # 携带作者数据渲染页面
    data = {
        "author":author.to_dict(),
        "user_info":g.user.to_dict() if g.user else ""
    }
    return render_template("news/other.html",data=data)


# 功能描述：获取发布的新闻列表
@profile_blue.route('/news_list')
@user_login_data
def news_list():
    # 获取参数
    page = request.args.get('p',"1")
    # 转换参数类型
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 分页查询
    try:
        paginate = News.query.filter(News.user_id == g.user.id).order_by(News.create_time.desc()).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")
    # 获取分页对象属性，总页数，当前页，对象列表
    totalPage = paginate.pages
    currentPage= paginate.page
    items = paginate.items

    # 对象列表转换成字典列表
    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())
    # 拼接数据，渲染页面
    data = {
        "totalPage":totalPage,
        "currentPage":currentPage,
        "news_list":news_list
    }

    return render_template("news/user_news_list.html",data=data)




# 功能描述：新闻发布
@profile_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    # 如果是GET 请求，携带分类渲染页面
    if request.method == "GET":
        # 查询所有分类
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="获取分类失败")

        # 对象列表转换为字典列表
        category_list = []
        for category in categories:
            category_list.append(category.to_dict())
        return render_template("news/user_news_release.html",categories=category_list)

    # 如果是post请求，获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")

    # 校验参数，为空校验
    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    # 上传图片，并判断是否上传成功
    try:
       image_name = image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="七牛云上传失败")
    if not image_name:return jsonify(errno=RET.NODATA,errmsg="图片上传失败")
    # 创建新闻对象，社会新闻属性
    news = News()
    news.title = title
    news.source = g.user.nick_name
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX+image_name
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1 #审核中
    # 保存新闻到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="新闻发布失败")
    # 返回响应
    return jsonify(errno=RET.OK,errmsg="新闻发布成功")


# 功能描述：获取我的收藏
@profile_blue.route('/collection')
@user_login_data
def collection():
    # 获取参数
    page = request.args.get("p",1)
    # 参数类型转换
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page =1
    # 分页查询
    try:
       paginate =  g.user.collection_news.order_by(News.create_time.desc()).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")
    # 获取分页对象属性，总页数，当前页，当前页对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 将新闻对象列表转为字典列表
    news_list = []
    for item in items:
        news_list.append(item.to_dict())
    # 携带数据渲染页面
    data = {
        "totalPage":totalPage,
        "currentPage":currentPage,
        "news_list":news_list
    }

    return render_template("news/user_collection.html",data=data)


# 功能描述：修改密码
@profile_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    # 判断请求方式，如果为GET请求则携带数据渲染页面
    if request.method == "GET":
        # 判断用户是否登陆
        # if not g.user:
        #     return redirect("/")
        return render_template("news/user_pass_info.html")
    # 如果为POST，获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    # 校验参数，为空校验
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    # 判断就密码是否正确
    if not g.user.check_password(old_password):
        return jsonify(errno=RET.DATAERR,errmsg="旧密码错误")
    # 将新密码设置到用户对象
    g.user.password = new_password

    # 清除用户登陆信息
    session.pop("user_id",None)
    session.pop("nick_name",None)
    session.pop("mobile",None)
    # 返回响应
    return jsonify(errno=RET.OK,ermsg="修改成功")


# 功能描述：图片上传
@profile_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    # 判断请求方式如果是GET请求，携带数据渲染页面
    if request.method == "GET":
        return render_template("news/user_pic_info.html",user=g.user.to_dict())
    # 如果是POST ，获取参数
    avatar = request.files.get("avatar")
    # 校验参数
    if not avatar:
        return jsonify(errno=RET.PARAMERR,errmsg="参数")
    # 上传图片，判断是否上传成功
    try:
        image_name = image_storage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="七牛云异常")
    if not image_name: return jsonify(errno=RET.NODATA,errmsg="图片上传失败")
    # 设置图片到用户对象
    g.user.avatar_url = image_name
    # 返回响应，返回图片地址
    data = {
        "avatar_url":constants.QINIU_DOMIN_PREFIX+image_name
    }
    return jsonify(errno=RET.OK,errmsg="上传成功",data=data)

@profile_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    # 1,判断如果是GET 请求，携带数据展示页面
    if request.method == "GET":
        return render_template('news/user_base_info.html',user=g.user.to_dict())
    # 如果是post请求，获取参数，
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")
    # 校验参数，为空校验
    if not all([signature,nick_name,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    # 校验性别
    if not gender in ["MAN","WOMAN"]:
        return jsonify(errno=RET.DATAERR,errmsg="性别有误")

    # 更新数据到用户对象中
    try:
        g.user.signature = signature
        g.user.nick_name = nick_name
        g.user.gender = gender
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="修改失败")
    # 返回响应
    return jsonify(errno=RET.OK,errmsg="修改成功")


# 功能描述：用户界面展示
@profile_blue.route("/info",methods=["GET","POST"])
@user_login_data
def user_info():

    if not g.user:
        return redirect("/")

    # 携带用户数据渲染页面
    data = {
        "user_info":g.user.to_dict()
    }
    return render_template("news/user.html",data=data)
